package it.okkam.longwell.ui.command;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import sun.security.action.GetLongAction;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.util.FileManager;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.LongwellServlet;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.CommandBase;

public class AdministrationDatasetsCommand extends CommandBase {
	final static private Logger s_logger = Logger
			.getLogger(AdministrationCommand.class);
	protected ServletContext context;
	public static boolean userInput = false;
	final protected String m_template;
	HashMap<String, String> userForSession = new HashMap<String, String>();

	public AdministrationDatasetsCommand(InjectionManager injectionManager,
			String template) {
		super(injectionManager);
		m_template = template;
	}

	public void execute(FlairMessage msg) throws ServletException {
		try {
			VelocityContext vcContext = createContext(msg);
			HttpSession session = msg.m_request.getSession();
			String sessionId = msg.m_request.getSession().getId();
			String username = msg.getProfile(sessionId).getUserName();
			context = msg.m_servlet.getServletContext();
			String fileName = LongwellServer.getUsersDatasetPath(); 
			vcContext.put("usersToValidate", getUsersToValidate(msg));
			vcContext.put("usersRegistered", getUsersRegistered(msg));
			vcContext.put("usersAdministrator", getAdministrators(msg));		
			msg.m_ve.mergeTemplate("templates/commands/administration_users.vt",
					vcContext, msg.m_response.getWriter());
			//}
		} catch (Exception e) {
			s_logger.error(e);
			e.printStackTrace();
		}

	}


	
	protected Set getUsersToValidate(FlairMessage msg) {
		//Model model = loadInputModel(msg);
		//Model model = LongwellServer.getBCCDataset().getDefaultModel();
		Model model = LongwellServer.getBCCDataset().getNamedModel("http://www.provincia.tn.it/bcc/resource/bcc-utenti");
		String queryString =

		"PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
				+ "PREFIX : <http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#> "
				+ "SELECT ?member " + "WHERE {"
				+ "      :rivela_pending foaf:member ?member . " + "      }";

		Query query = QueryFactory.create(queryString);

		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();

		Set members = new HashSet<String>();
		while (results.hasNext()) {
			QuerySolution member = results.next();
			String user = member.get("member").toString();
			// members.add(member.get("member"));

			queryString =

			"PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
					+ "PREFIX : <http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#> "
					+ "SELECT ?nickname ?mbox " + "WHERE {" + "      <" + user
					+ "> foaf:nickname ?nickname;" + "foaf:mbox ?mbox . "
					+ "      }";
			query = QueryFactory.create(queryString);
			QueryExecution qe2 = QueryExecutionFactory.create(query, model);
			ResultSet results2 = qe2.execSelect();
			QuerySolution member2 = results2.next();
			//normal user with username and pwd, no webid
			if(user.startsWith("http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#")){
				members.add(member2.get("nickname") + "|" + member2.get("mbox"));
			}
			else if (!user.startsWith("http://www.okkam.it/bcc/login")){ 
				members.add(member2.get("nickname") + "|" + member2.get("mbox")+"@@@@"+user);
			}
			qe2.close();
		}
		qe.close();
		return members;
	}
	

	
	protected Set getUsersRegistered(FlairMessage msg) {
		//Model model = loadInputModel(msg);
		//Model model = LongwellServer.getBCCDataset().getDefaultModel();
		Model model = LongwellServer.getBCCDataset().getNamedModel("http://www.provincia.tn.it/bcc/resource/bcc-utenti");

		String queryString =

		"PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
				+ "PREFIX : <http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#> "
				+ "SELECT ?member " + "WHERE {"
				+ "      :rivela_user foaf:member ?member . " + "      }";

		Query query = QueryFactory.create(queryString);

		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();

		Set members = new HashSet<String>();
		while (results.hasNext()) {
			QuerySolution member = results.next();
			String user = member.get("member").toString();			
			// members.add(member.get("member"));

			queryString =

			"PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
					+ "PREFIX : <http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#> "
					+ "SELECT ?nickname ?mbox " + "WHERE {" + "      <" + user
					+ "> foaf:nickname ?nickname;" + "foaf:mbox ?mbox . "
					+ "      }";
			query = QueryFactory.create(queryString);
			QueryExecution qe2 = QueryExecutionFactory.create(query, model);
			ResultSet results2 = qe2.execSelect();
			QuerySolution member2 = results2.next();
			//normal user with username and pwd, no webid
			if(user.startsWith("http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#")){
				members.add(member2.get("nickname") + "|" + member2.get("mbox"));
			}
			else if (!user.startsWith("http://www.okkam.it/bcc/login")){
				members.add(member2.get("nickname") + "|" + member2.get("mbox")+"@@@@"+user);
			}
			qe2.close();
		}
		qe.close();
		return members;
	}	

	protected Set getAdministrators(FlairMessage msg) {
		//Model model = loadInputModel(msg);
		//Model model = LongwellServer.getBCCDataset().getDefaultModel();
		Model model = LongwellServer.getBCCDataset().getNamedModel("http://www.provincia.tn.it/bcc/resource/bcc-utenti");

		String queryString =

		"PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
				+ "PREFIX : <http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#> "
				+ "SELECT ?member " + "WHERE {"
				+ "      :rivela_admin foaf:member ?member . " + "      }";

		Query query = QueryFactory.create(queryString);

		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();

		Set members = new HashSet<String>();
		while (results.hasNext()) {
			QuerySolution member = results.next();
			String user = member.get("member").toString();
			// members.add(member.get("member"));

			queryString =

			"PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
					+ "PREFIX : <http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#> "
					+ "SELECT ?nickname ?mbox " + "WHERE {" + "      <" + user
					+ "> foaf:nickname ?nickname;" + "foaf:mbox ?mbox . "
					+ "      }";
			query = QueryFactory.create(queryString);
			QueryExecution qe2 = QueryExecutionFactory.create(query, model);
			ResultSet results2 = qe2.execSelect();
			QuerySolution member2 = results2.next();
			//normal user with username and pwd, no webid
			if(user.startsWith("http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#")){
				members.add(member2.get("nickname") + "|" + member2.get("mbox"));
			}
			else if (!user.startsWith("http://www.okkam.it/bcc/login")){
				members.add(member2.get("nickname") + "|" + member2.get("mbox")+"@@@@"+user);
			}
			qe2.close();
		}
		qe.close();
		return members;
	}		
}
